tool
extends Control

const basePath  = "res://addons/myplug/nodes/" # 自定义节点存放路径


onready var nodesCtn = $"vbox/nodes" # 自定义节点按钮容器
onready var addNewDlg = $"addNewDlg" # 新建自定义节点对话框

onready var extClass = $"addNewDlg/GridContainer/ext" # 继承自
onready var nodeName = $"addNewDlg/GridContainer/nameTxt" # 节点名称
onready var nodeIcon = $"addNewDlg/GridContainer/icon" # 图标

var nodes:Array = myFile.file_filter(basePath,".gd") # nodes目录下的GD脚本（自定义节点类）的集合

func _enter_tree():
	var _nodesCtn = $"vbox/nodes" # 自定义节点按钮容器
	# 加载自定义节点按钮
	if _nodesCtn.get_child_count() == 0 and get_parent() is TabContainer:
		for node in nodes:
			var btn = Button.new()
			btn.text = node.replace(".gd","")
			btn.icon = get_icon("Node","EditorIcons")
			btn.size_flags_horizontal = SIZE_EXPAND_FILL
			_nodesCtn.add_child(btn)
			btn.owner = _nodesCtn
			btn.connect("pressed",self,"btn_click",[node.replace(".gd","")])
		
# 将自定义类型节点添加到当前场景选中节点		
func btn_click(nodeType:String):
	var MyClass = load(basePath + nodeType + ".gd") # 加载自定义节点代码
	if MyClass:
		var node = MyClass.new() # 创建实例
		node.name = nodeType # 将名称定为自定义控件名
		if sel():
			sel().add_child(node) # 添加自定义控件到当前场景选中节点
			# 创建继承脚本
			var code = "extends " + nodeType + "\n"
			var times = myDateTime.time_sequence() # 当前日期时间序列字符串
			var gdPath = basePath + "ins/" + node.name + "." + times +".ins.gd"
			myFile.saveString(gdPath,code) # 创建继承脚本
			node.set_script(load(gdPath))
			node.owner = get_tree().edited_scene_root # 设置owner为场景根节点	

# 判断并返回当前场景中选中的节点
func sel() -> Node:
	var plug = EditorPlugin.new()
	var sels = plug.get_editor_interface().get_selection().get_selected_nodes() # 获取当前选中的节点集合
	var _sel
	if sels.size() == 1:
		_sel =sels[0]
	else:
		_sel = null
	return _sel

# “新建自定义节点”按钮单击
func _on_addNewBtn_pressed():
	addNewDlg.popup()
	pass 

# 对话框 - “创建”按钮
func _on_addBtn_pressed():
	# == 创建自定义节点脚本 ==
	# 获取模板代码
	var conf = ConfigFile.new()
	conf.load("res://addons/myplug/nodes/node.tpl")
	var code:String = conf.get_value("tpl","code")
	# 替换字符串
	code = code.replace("{{class}}",extClass.text)
	code = code.replace("{{name}}",nodeName.text)
	code = code.replace("{{icon}}","icons/myButton.png")
	# 创建脚本文件
	
	myFile.saveString(basePath + nodeName.text + ".gd",code)
	# 添加新的按钮到自定义节点库列表
	var btn = Button.new()
	btn.text = nodeName.text
	btn.icon = get_icon(nodeIcon.text,"EditorIcons")
	btn.size_flags_horizontal = SIZE_EXPAND_FILL
	nodesCtn.add_child(btn)
	btn.owner = nodesCtn
	btn.connect("pressed",self,"btn_click",[nodeName.text])
	addNewDlg.hide()
	pass 
